import axios from 'axios';

// 声明全局API配置类型
declare global {
  interface Window {
    API_CONFIG?: {
      BASE_URL: string;
    };
  }
}

// 自动识别当前访问的主机名，如果不是localhost则使用当前主机名
// 这样当通过IP地址访问前端时，API请求也会自动使用相同的IP地址
const getAPIBaseURL = () => {
  // 首先检查全局配置是否存在（从index.html中注入）
  if (window.API_CONFIG?.BASE_URL) {
    console.log('使用全局配置的API地址:', window.API_CONFIG.BASE_URL);
    return window.API_CONFIG.BASE_URL;
  }

  // 获取当前访问的主机名
  const hostname = window.location.hostname;
  const port = "9001"; // 服务器端口
  
  console.log('当前访问主机名:', hostname);
  
  // 如果已通过环境变量配置了API基础URL，使用环境变量
  if (import.meta.env.VITE_API_BASE_URL) {
    console.log('使用环境变量API地址:', import.meta.env.VITE_API_BASE_URL);
    return import.meta.env.VITE_API_BASE_URL;
  }
  
  // 构建API URL
  const apiUrl = `http://${hostname}:${port}/api`;
  console.log('自动构建API地址:', apiUrl);
  return apiUrl;
};

const API_BASE_URL = getAPIBaseURL();

console.log('最终API基础URL:', API_BASE_URL);

const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000, // 增加超时时间，避免网络不佳时请求失败
  withCredentials: false // 跨域请求时不携带凭证
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const timestamp = new Date().toISOString();
    console.log('发送请求:', {
      timestamp,
      method: config.method?.toUpperCase(),
      url: config.url,
      baseURL: config.baseURL,
      fullURL: `${config.baseURL}${config.url}`,
      data: config.data,
      headers: config.headers
    });
    return config;
  },
  (error) => {
    console.error('请求拦截器错误:', {
      error,
      timestamp: new Date().toISOString()
    });
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    const timestamp = new Date().toISOString();
    console.log('收到响应:', {
      timestamp,
      status: response.status,
      statusText: response.statusText,
      headers: response.headers,
      data: response.data,
      config: {
        method: response.config.method?.toUpperCase(),
        url: response.config.url,
        baseURL: response.config.baseURL
      }
    });
    return response;
  },
  (error) => {
    console.error('响应拦截器错误:', {
      timestamp: new Date().toISOString(),
      error: {
        message: error.message,
        code: error.code,
        stack: error.stack
      },
      config: error.config,
      response: error.response ? {
        status: error.response.status,
        statusText: error.response.statusText,
        data: error.response.data,
        headers: error.response.headers
      } : null
    });
    return Promise.reject(error);
  }
);

export interface PrinterFormData {
  name: string;
  ip: string;
  port: number;
  protocol: 'RAW' | 'IPP';
  description?: string;
}

export interface Printer extends PrinterFormData {
  id: string;
  isOnline: boolean;
  lastOnline: Date;
  isSystemPrinter?: boolean;
}

export interface SystemPrinter {
  name: string;
  driverName: string;
  portName: string;
  status: number;
  statusText: string;
  isReady: boolean;
}

// 统一的打印机类型，包含系统打印机和网络打印机的所有属性
export interface UnifiedPrinter {
  id: string;
  name: string;
  ip?: string;
  port?: number;
  protocol?: string;
  description?: string;
  isOnline?: boolean;
  isReady?: boolean;
  isSystem?: boolean; // 标识是否为系统打印机
  isSystemPrinter?: boolean; // 兼容旧版本
  status?: number;
  statusText?: string;
  driverName?: string;
  portName?: string;
  lastOnline?: Date;
}

export interface ScanResult {
  message: string;
  count: number;
  printers: Printer[];
}

export interface PrintTaskParams {
  copies?: number;
  color?: boolean;
  colorMode?: 'auto' | 'color' | 'auto-monochrome' | 'monochrome';
  quality?: 'draft' | 'normal' | 'high';
  format?: 'image/urf' | 'image/pwg-raster' | 'application/octet-stream' | 'application/pdf';
}

export interface PrintTask {
  id: string;
  name: string;
  originalName: string;
  status: 'pending' | 'printing' | 'completed' | 'failed';
  createdAt: Date;
  completedAt?: Date;
  copies: number;
  color: boolean;
  colorMode?: 'auto' | 'color' | 'auto-monochrome' | 'monochrome';
  quality?: 'draft' | 'normal' | 'high';
  format?: 'image/urf' | 'image/pwg-raster' | 'application/octet-stream' | 'application/pdf';
  duplex: boolean;
  printerId: number;
  fileId: string;
  size: number;
  type: string;
  errorMessage?: string;
}

export interface FileItem {
  id: string;
  name: string;
  originalName: string;
  size: number;
  type: string;
  createdAt: Date;
}

class PrinterAPI {
  async getPrinters(): Promise<{ printers: Printer[] }> {
    console.log('调用 getPrinters 方法');
    try {
      const response = await api.get('/printers');
      console.log('获取打印机列表响应:', {
        response: response.data,
        timestamp: new Date().toISOString()
      });

      // 如果响应是数组，包装成对象
      if (Array.isArray(response.data)) {
        return { printers: response.data };
      }
      // 如果响应已经是对象，直接返回
      return response.data;
    } catch (error: any) {
      console.error('获取打印机列表失败:', {
        error,
        message: error.message,
        response: error.response?.data,
        timestamp: new Date().toISOString()
      });
      throw error;
    }
  }

  async getSystemPrinters(): Promise<SystemPrinter[]> {
    console.log('调用 getSystemPrinters 方法');
    try {
      const response = await api.get('/printers/system');
      console.log('获取系统打印机列表响应:', {
        response: response.data,
        timestamp: new Date().toISOString()
      });

      return response.data;
    } catch (error: any) {
      console.error('获取系统打印机列表失败:', {
        error,
        message: error.message,
        response: error.response?.data,
        timestamp: new Date().toISOString()
      });
      throw error;
    }
  }

  async syncSystemPrinters(): Promise<{ success: boolean; message: string; printers: Printer[] }> {
    console.log('调用 syncSystemPrinters 方法');
    try {
      const response = await api.post('/printers/sync');
      console.log('同步系统打印机响应:', {
        response: response.data,
        timestamp: new Date().toISOString()
      });

      return response.data;
    } catch (error: any) {
      console.error('同步系统打印机失败:', {
        error,
        message: error.message,
        response: error.response?.data,
        timestamp: new Date().toISOString()
      });
      throw error;
    }
  }

  async getPrinter(id: string): Promise<Printer> {
    console.log('调用 getPrinter 方法:', { id });
    const response = await api.get(`/printers/${id}`);
    return response.data;
  }

  async addPrinter(printerData: PrinterFormData): Promise<Printer> {
    console.log('调用 addPrinter 方法:', { 
      printerData,
      timestamp: new Date().toISOString()
    });

    // 确保数据格式正确
    const formattedData = {
      name: printerData.name.trim(),
      ip: printerData.ip.trim(),
      port: parseInt(printerData.port.toString()),
      protocol: printerData.protocol.toUpperCase(),
      description: printerData.description?.trim() || '',
      isOnline: false,
      taskCount: 0,
      lastOnline: null,
      todayPrintCount: 0,
      failedPrintCount: 0
    };

    console.log('格式化后的数据:', {
      formattedData,
      timestamp: new Date().toISOString()
    });

    try {
      const response = await api.post('/printers', formattedData);
      console.log('添加打印机成功:', {
        response: response.data,
        timestamp: new Date().toISOString()
      });
      return response.data;
    } catch (error: any) {
      console.error('添加打印机失败:', {
        error,
        message: error.message,
        response: error.response?.data,
        timestamp: new Date().toISOString()
      });
      throw error;
    }
  }

  async updatePrinter(id: string, printerData: Partial<PrinterFormData>): Promise<Printer> {
    console.log('调用 updatePrinter 方法:', { id, printerData });
    const response = await api.put(`/printers/${id}`, printerData);
    return response.data;
  }

  async deletePrinter(id: string): Promise<{ success: boolean; message: string }> {
    console.log('调用 deletePrinter 方法:', { 
      id,
      timestamp: new Date().toISOString() 
    });
    
    try {
      const response = await api.delete(`/printers/${id}`);
      console.log('删除打印机成功:', {
        response: response.data,
        timestamp: new Date().toISOString()
      });
      
      return {
        success: true,
        message: '打印机已成功删除'
      };
    } catch (error: any) {
      console.error('删除打印机失败:', {
        error,
        message: error.message,
        response: error.response?.data,
        status: error.response?.status,
        timestamp: new Date().toISOString()
      });
      
      // 构建详细的错误信息
      let errorMessage = '删除打印机失败';
      if (error.response?.data?.message) {
        errorMessage = error.response.data.message;
      } else if (error.response?.data?.error) {
        errorMessage = error.response.data.error;
      } else if (error.message) {
        errorMessage = error.message;
      }
      
      return {
        success: false,
        message: errorMessage
      };
    }
  }

  async scanPrinters(startIP: string, endIP: string): Promise<{ printers: PrinterFormData[] }> {
    console.log('调用 scanPrinters 方法:', {
      startIP,
      endIP,
      timestamp: new Date().toISOString()
    });

    try {
      const response = await api.post('/printers/scan', { 
        startIP, 
        endIP,
      });
      return response.data;
    } catch (error: any) {
      console.error('扫描打印机失败:', {
        error,
        message: error.message,
        response: error.response?.data,
        timestamp: new Date().toISOString()
      });
      throw error;
    }
  }

  async uploadFile(file: File, printerId: number): Promise<FileItem> {
    console.log('调用 uploadFile 方法:', {
      fileName: file.name,
      fileSize: file.size,
      printerId,
      timestamp: new Date().toISOString()
    });

    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('printerId', printerId.toString());

      const response = await api.post('/files/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });

      console.log('文件上传成功:', {
        response: response.data,
        timestamp: new Date().toISOString()
      });

      return response.data;
    } catch (error: any) {
      console.error('文件上传失败:', {
        error,
        message: error.message,
        response: error.response?.data,
        timestamp: new Date().toISOString()
      });
      throw error;
    }
  }

  async getPrinterTasks(printerId: string): Promise<PrintTask[]> {
    console.log('调用 getPrinterTasks 方法:', { printerId });
    const response = await api.get(`/printers/${printerId}/tasks`);
    return response.data;
  }

  async startPrintTask(printerId: string, taskId: string, options: { copies: number; color: boolean; duplex: boolean }): Promise<PrintTask> {
    console.log('调用 startPrintTask 方法:', { printerId, taskId, options });
    const response = await api.post(`/printers/${printerId}/tasks/${taskId}/start`, options);
    return response.data;
  }

  async getPrinterFiles(printerId: string): Promise<FileItem[]> {
    console.log('调用 getPrinterFiles 方法:', { printerId });
    const response = await api.get(`/printers/${printerId}/files`);
    return response.data;
  }

  async deleteFile(fileId: string): Promise<void> {
    console.log('调用 deleteFile 方法:', { fileId });
    await api.delete(`/files/${fileId}`);
  }

  async createTask(printerId: number, fileId: string, options: PrintTaskParams = {}): Promise<PrintTask> {
    console.log('调用 createTask 方法:', { printerId, fileId, options });
    const response = await api.post(`/printers/${printerId}/tasks`, {
      fileId,
      ...options
    });
    return response.data;
  }

  async deleteTask(printerId: string, taskId: string): Promise<void> {
    console.log('调用 deleteTask 方法:', { printerId, taskId });
    await api.delete(`/printers/${printerId}/tasks/${taskId}`);
  }

  async printTask(printerId: string, taskId: string): Promise<{ message: string; success: boolean; jobId?: string; error?: string }> {
    console.log('调用 printTask 方法:', { 
      printerId, 
      taskId,
      timestamp: new Date().toISOString()
    });
    
    try {
      const response = await api.post(`/printers/${printerId}/tasks/${taskId}/print`);
      console.log('打印任务完成:', {
        data: response.data,
        timestamp: new Date().toISOString()
      });
      
      // 确保返回对象包含成功状态
      return { 
        ...response.data,
        success: true 
      };
    } catch (error: any) {
      console.error('打印任务失败:', {
        error,
        message: error.message,
        response: error.response?.data,
        status: error.response?.status,
        timestamp: new Date().toISOString()
      });
      
      // 构建详细的错误信息
      let errorMessage = '打印失败';
      if (error.response?.data?.message) {
        errorMessage = error.response.data.message;
      } else if (error.response?.data?.error) {
        errorMessage = error.response.data.error;
      } else if (error.message) {
        errorMessage = error.message;
      }
      
      // 返回包含错误信息的对象
      return {
        message: errorMessage,
        success: false,
        error: errorMessage
      };
    }
  }

  // 获取所有打印机（包括系统打印机和网络打印机）
  async getAllPrinters(): Promise<{ printers: (Printer | SystemPrinter)[], count: number }> {
    console.log('调用 getAllPrinters 方法');
    try {
      const response = await api.get('/printers/all');
      console.log('获取所有打印机列表响应:', {
        response: response.data,
        timestamp: new Date().toISOString()
      });

      return response.data;
    } catch (error: any) {
      console.error('获取所有打印机列表失败:', {
        error,
        message: error.message,
        response: error.response?.data,
        timestamp: new Date().toISOString()
      });
      // 如果获取失败，返回空列表
      return { printers: [], count: 0 };
    }
  }
}

export const printerApi = new PrinterAPI(); 